package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Menu;
import com.itheima.service.MenuService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/authenty")
public class PageAuthentyController {

    @RequestMapping("/checkgroup")
    public Map<String, Boolean> checkgroup() {
        Map<String, Boolean> map = new HashMap<String, Boolean>();
        map.put("add", false);
        map.put("edit", false);
        map.put("delete", false);

        //获取权限集合
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Collection<GrantedAuthority> authorities = user.getAuthorities();
        for (GrantedAuthority authority : authorities) {
            //获取权限的关键字
            String keyword = authority.getAuthority();
            if ("CHECKGROUP_ADD".equals(keyword)) {
                map.put("add", true);
                continue;
            }
            if ("CHECKGROUP_EDIT".equals(keyword)) {
                map.put("edit", true);
                continue;
            }
            if ("CHECKGROUP_DELETE".equals(keyword)) {
                continue;
            }
        }
        return map;
    }

    @RequestMapping("/checkitem")
    public Map<String, Boolean> checkitem() {
        Map<String, Boolean> map = new HashMap<String, Boolean>();
        map.put("add", false);
        map.put("edit", false);
        map.put("delete", false);

        //获取权限集合
        Collection<GrantedAuthority> authorities = (Collection<GrantedAuthority>) SecurityContextHolder.getContext().getAuthentication().getAuthorities();
        for (GrantedAuthority authority : authorities) {
            //获取权限的关键字
            String keyword = authority.getAuthority();
            if ("CHECKITEM_ADD".equals(keyword)) {
                map.put("add", true);
                continue;
            }
            if ("CHECKITEM_EDIT".equals(keyword)) {
                map.put("edit", true);
                continue;
            }
            if ("CHECKITEM_DELETE".equals(keyword)) {
                continue;
            }
        }
        return map;
    }

    @Reference
    private MenuService menuService;

    @RequestMapping("/menu")
    public Result menu(String username) {
        List<Menu> list = menuService.findMenu(username);
        return new Result(true,MessageConstant.GET_BUSINESS_REPORT_FAIL,list);
    }
}
